<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\WorkMoment\Task;

use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\Plugin\WorkMoment\Queue\MomentCommentQueue;
use MoChat\Plugin\WorkMoment\Queue\MomentQueue;
use MoChat\Plugin\WorkMoment\Queue\MomentTaskQueue;

/**
 * 每小时执行一次
 * @Crontab(name="MomentTask", rule="0 * * * *", callback="execute", singleton=true, memo="企业微信-客户朋友圈")
 */
class MomentTask
{
    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var MomentQueue
     */
    protected $momentQueue;

    /**
     * @Inject
     * @var MomentTaskQueue
     */
    protected $momentTaskQueue;

    /**
     * @Inject
     * @var MomentCommentQueue
     */
    protected $momentCommentQueue;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function execute(): void
    {
        $corps = $this->corpService->getCorps(['id', 'wx_corpid', 'employee_secret', 'contact_secret']);
        foreach ($corps as $item) {
            if (empty($item['wxCorpid'])
                || empty($item['employeeSecret'])
                || empty($item['contactSecret'])
            ) {
                continue;
            }
            // 异步处理
            try {
                // 企业全部的发表列表
                $this->momentQueue->handle($item['id']);
                // 企业发表的朋友圈成员执行情况
                $this->momentTaskQueue->handle($item['id']);
                // 客户朋友圈的互动数据
                $this->momentCommentQueue->handle($item['id']);
            } catch (InvalidConfigException|GuzzleException $e) {
                $this->logger->error('客户朋友圈异步调用失败' . $e->getMessage());
            }
        }
        $this->logger->info('客户朋友圈统计完成');
    }
}
